<template>
    <div class="common-layout">
        <el-container style="height: 100%;">
            <el-header class="nav">
                <img src="@/assets/logo.svg" class="logo">
                <span class="title">跑腿猫</span>
                <div class="tag" :class="{ close: tempRadio === 0 }">{{ storeStatus }}</div>
                <div class="info">
                    <el-button color="#FFD580" :icon="Clock" class="statusBtn" @click="openStatusDialog">
                        营业状态设置
                    </el-button>
                    <el-dropdown>
                        <el-button color="#FFD580" class="statusBtn">
                            <img src="@/assets/avatar.jpeg" class="avatar">
                            <span class="storename">果优鲜</span>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-item :icon="School" @click="openStoreInfoDrawer">店铺信息</el-dropdown-item>
                            <el-dropdown-item :icon="SwitchButton" @click="logout">退出登录</el-dropdown-item>
                        </template>
                    </el-dropdown>
                </div>
            </el-header>
            <el-container>
                <el-aside width="240px">
                    <el-menu :default-active="activeMenuIndex" active-text-color="#ff9a00" class="aside" background-color="#fff"
                        @select="handleMenuSelect">
                        <el-menu-item v-for="item in menuItems" :key="item.index" :index="item.index">
                            <el-icon>
                                <component :is="item.icon" />
                            </el-icon>
                            <span>{{ item.title }}</span>
                        </el-menu-item>
                    </el-menu>
                </el-aside>
                <el-main>
                    <div class="main">
                        <router-view />
                    </div>
                </el-main>
            </el-container>
        </el-container>

        <!-- 营业状态设置对话框 -->
        <el-dialog v-model="dialogTableVisible" title="营业状态设置" width="400">
            <el-radio-group v-model="radio" class="radio">
                <div class="radioBox" :class="{ active: radio === '1' }" @click="radio = '1'">
                    <el-radio value="1">营业</el-radio>
                    <div class="desc">
                        当餐厅处于营业状态，自动接收任何订单，可点击打烊进入店铺打烊状态。
                    </div>
                </div>
                <div class="radioBox" :class="{ active: radio === '0' }" @click="radio = '0'">
                    <el-radio value="0">打烊</el-radio>
                    <div class="desc">
                        当餐厅处于打烊状态，仅接受营业时间内的预定订单，可点击营业中手动恢复营业状态。
                    </div>
                </div>
            </el-radio-group>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelStatusChange" class="cancelBtn btn">取消</el-button>
                    <el-button type="primary" @click="confirmStatusChange" class="btn" color="#ffc200">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 店铺信息抽屉 -->
        <el-drawer v-model="drawer">
            <template #header>
                <h4>店铺资料</h4>
            </template>
            <StoreInfoPage />
        </el-drawer>
    </div>
</template>

<script setup lang='ts'>
import { ref, markRaw, computed, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { merchantLogout } from '@/services/api/merchant'
import StoreInfoPage from '@/views/home/components/mine/components/StoreInfo.vue'
import { ElMessageBox } from 'element-plus'
import {
    Menu,
    Document,
    Burger,
    Dish,
    Goods,
    Coin,
    Clock,
    SwitchButton,
    School,
    Message
} from '@element-plus/icons-vue'
import { getStoreInfo, setStoreStatus } from '@/services/api/store'
import { useStoreInfoStore } from '@/store'

// Router and Store
const router = useRouter()
const route = useRoute()
const storeInfoStore = useStoreInfoStore()

// Reactive References
const dialogTableVisible = ref(false)
const drawer = ref(false)
const radio = ref('0')
const tempRadio = ref(0)
const activeMenuIndex = ref('1')

// Computed Properties
const storeStatus = computed(() => {
    return tempRadio.value === 1 ? '营业中' : '已打烊'
})

// Menu Items
const menuItems = ref([
    { index: '1', title: '工作台', icon: markRaw(Menu) },
    { index: '2', title: '订单管理', icon: markRaw(Document) },
    { index: '3', title: '菜品管理', icon: markRaw(Dish) },
    { index: '4', title: '套餐管理', icon: markRaw(Burger) },
    { index: '5', title: '分类管理', icon: markRaw(Coin) },
    { index: '6', title: '我的店铺', icon: markRaw(Goods) },
    { index: '7', title: '我的消息', icon: markRaw(Message) },
])

// Lifecycle
onBeforeMount(async () => {
    await initializeStoreInfo()
    updateActiveMenu()
})

// Methods
const initializeStoreInfo = async () => {
    try {
        const res = await getStoreInfo()
        storeInfoStore.setStoreInfo(res.data)
        radio.value = storeInfoStore.storeInfo?.status === 1 ? '1' : '0'
        tempRadio.value = parseInt(radio.value)
    } catch (error) {
        console.error('获取店铺信息失败:', error)
    }
}

const updateActiveMenu = () => {
    const routeMap: Record<string, string> = {
        '/home': '1',
        '/home/dish': '3',
        '/home/mine': '6'
    }

    activeMenuIndex.value = routeMap[route.path] || '1'
}

const openStatusDialog = () => {
    dialogTableVisible.value = true
    radio.value = tempRadio.value.toString()
}

const cancelStatusChange = () => {
    dialogTableVisible.value = false
}

const confirmStatusChange = async () => {
    try {
        const storeId = storeInfoStore.getField('storeId')
        const status = parseInt(radio.value)

        const res = await setStoreStatus(storeId, status)
        if (res.code === 200) {
            storeInfoStore.setStoreStatus(status)
            tempRadio.value = status
            dialogTableVisible.value = false
        }
    } catch (error) {
        console.error('设置店铺状态失败:', error)
    }
}

const handleMenuSelect = (index: string) => {
    const routeMap: Record<string, string> = {
        '1': '/home',
        '3': '/home/dish',
        '6': '/home/mine',
        '7': '/home/message'
    }

    const path = routeMap[index]
    if (path) {
        router.push(path)
    } else {
        console.warn(`No route defined for menu index: ${index}`)
    }
}

const openStoreInfoDrawer = () => {
    drawer.value = true
}

const logout = () => {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        merchantLogout()
        localStorage.removeItem('token')
        router.push('/login')
    }).catch(() => {
        // 取消操作
    })

}
</script>

<style lang='scss' scoped>
/* 样式部分保持不变 */
.common-layout {
    height: 100vh;
}

.nav {
    height: 70px;
    display: flex;
    align-items: center;
    background-color: #FFD580;
    backdrop-filter: blur(10px);
}

.logo {
    width: 70px;
    height: 60px;
    margin-left: 5px;
    margin-right: 10px;
}

.title {
    color: #663300;
    font-size: 28px;
    font-weight: 600;
    margin-right: 30px;
}

.tag {
    padding: 0px 6px;
    color: #fff;
    border: 1px solid #fff;
    border-radius: 4px;
    background-color: #fd3333;
}

.tag.close {
    background-color: #6A6A6A;
}

.info {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.statusBtn {
    height: 70px;
    margin-right: 15px;
    color: #663300;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 12%;
    margin-right: 10px;
}

.storename {
    color: #663300;
}

.aside {
    height: 100%;
    // background-color: #f5f5f5;
}

:deep(.el-main) {
    padding: 0;
}

.main {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
}

.radio {
    display: flex;
    align-items: center;
    justify-content: center;
}

.radioBox {
    padding: 20px;
    width: 300px;
    border-radius: 8px;
    margin-bottom: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid #e6e6e6;
    background-color: white;
}

.radioBox:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.radioBox.active {
    border-color: #ffc200;
    background-color: #fff9f0;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.desc {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin-top: 8px;
    padding: 0;
}

:deep(.el-radio__label) {
    color: #666 !important;
}

:deep(.is-checked) {
    .el-radio__inner {
        background-color: #ffc200 !important;
        border: 1px solid #ffc200 !important;
    }
}

.btn {
    color: #333;
}

.cancelBtn:hover {
    color: #ffc200;
    border-color: #ffc200;
    background-color: #fffbf0;
}
</style>